/* Copyright (c) 2022 渝州大数据实验室
 *
 * Lanius is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *
 *     http://license.coscl.org.cn/MulanPSL2
 *
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.yzbdl.lanius.orchestrate.serv.quartz.taskplan;

import java.util.List;
import java.util.Objects;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.yzbdl.lanius.orchestrate.common.entity.task.TaskPlan;
import org.yzbdl.lanius.orchestrate.common.enums.TaskStatusEnum;
import org.yzbdl.lanius.orchestrate.serv.service.task.TaskPlanService;
import org.yzbdl.lanius.orchestrate.serv.utils.TaskScheduleJobUtil;
import org.yzbdl.lanius.orchestrate.common.vo.task.schedule.AddTaskPlanJobVO;

import lombok.extern.slf4j.Slf4j;

/**
 * 任务编排定时任务初始化
 *
 * @author jinchunzhao@yzbdl.ac.cn
 * @date 2022-04-11 15:30
 */
@Slf4j
@Component
public class TaskPlanScheduleInit implements InitializingBean {

    @Autowired
    private TaskPlanService taskPlanService;

    @Override
    public void afterPropertiesSet() throws Exception {
        initTaskPlanSchedule();
    }

    /**
     * 启动后初始化负载的定时任务
     * <p>
     *     暂没有需求要指定负载策略
     * </p>
     *
     */
    private void initTaskPlanSchedule() {
        List<TaskPlan> taskPlans = taskPlanService.getAllListIgnoreTenantId();
        if (CollectionUtils.isEmpty(taskPlans)) {
            return;
        }

        TaskPlan taskPlan;
        AddTaskPlanJobVO addTaskPlanJobVO;
        for (int i = 0, len = taskPlans.size(); i < len; i++) {
            taskPlan = taskPlans.get(i);
            boolean isPause = Objects.equals(taskPlan.getStatus(), TaskStatusEnum.DISABLED.getCode());
            String jobGroupName = TaskScheduleJobUtil.buildJobGroupName(taskPlan.getOrgId());

            addTaskPlanJobVO = AddTaskPlanJobVO.builder().taskPlanId(taskPlan.getId()).async(false)
                .cron(taskPlan.getTaskCron()).isPause(isPause).nodeId(taskPlan.getServerProgramId())
                .jobGroupName(jobGroupName)
                    .taskPlanGroupId(taskPlan.getGroupId()).isIncrementalLog(true).isParallel(false)
                    .build();
            taskPlanService.addTaskJob(addTaskPlanJobVO);
        }
    }
}
